using Microsoft.AspNetCore.Mvc;
using MVC.Repository;
using MVC.Models;
using System.Linq;
using MVC.Parmar;
using Parmar;

namespace MVC.Controllers
{
    public class ProductController : Controller
    {
        public IActionResult Index()
        {
            var a = new EfRepository<Product>();
            var b =a.Table.Where(x=>x.IsDeleted==false).ToList();
            return View(b);
        }

        public IActionResult CreateOrEdit( int id)
        {
             var a = new EfRepository<Product>();
             var b = a.Table.Where(x=>x.Id==id).FirstOrDefault();
            return View(b);
        }

        public IActionResult Query(QueryParmar request)
        {
             var a = new EfRepository<Product>();
             var b = a.Table.Where(x=>x.IsDeleted==false 
             &&
             (x.ProductName.Contains(request.keyword)||
             (x.Remarks.Contains(request.keyword))
             )
             );
            return Json(b);
        }
        [HttpPost]
        public IActionResult Save(ProductParmar model)
        {
             var a = new EfRepository<Product>();

             if(model.Id>0)
             {
                 var d =a.GetById(model.Id);
                 if(d!=null)
                 {
                     d.ProductName = model.ProductName;
                     d.Supplier = model.Supplier;
                     d.Price = model.Price;
                     d.Stock = model.Stock;
                     d.Remarks = model.Remarks;
                     a.Update(d);
                 }
             }
             else
             {
                 a.Insert(
                     new Product
                     {
                         ProductName = model.ProductName,
                         Supplier = model.Supplier,
                         Price = model.Price,
                         Stock = model.Stock,
                         Remarks = model.Remarks
                     }
                 );
             }
            return Ok();
        }

        public IActionResult Delete(int id)
        {
             var a = new EfRepository<Product>();
             a.Delete(id);
            return RedirectToAction("Index");
        }
    }
}